<!--vue模板-->
<template>
  <div class="root">
    <div>
      <span class="basic">基础信息</span>
    </div>
    <el-form
      ref="formRel"
      :model="data"
      label-width="150px"
      style="max-width: 1000px; margin-top: 20px"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品类型:">
            <el-radio-group v-model="data.type">
              <el-radio value="1" size="large">反击破产品</el-radio>
              <el-radio value="2" size="large">鄂破产品</el-radio>
              <el-radio value="3" size="large">圆锥类产品</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品单位:">
            <el-input v-model="data.unit" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品编号:">
            <el-input v-model="data.code" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="产品名称:">
            <el-input v-model="data.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="封面图:">
            <el-upload
              class="avatar-uploader"
              :action="host + '/upload/img'"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="轮播图:">
            <el-upload
              v-model:file-list="fileList"
              class="avatar-uploader"
              :action="host + '/upload/img'"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :on-success="handleBannerSuccess"
            >
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>

            <el-dialog v-model="dialogVisible">
              <img w-full :src="dialogImageUrl" alt="Preview Image" />
            </el-dialog>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="产品分类:">
            <el-tree-select
              v-model="category"
              :data="productcategorys"
              :render-after-expand="false"
              style="width: 100%"
              :props="{
                children: 'children',
                label: 'dictName',
                value: 'dictName'
              }"
              @change="categoryChg"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="型号:">
            <el-select
              v-model="data.spec"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in specList"
                :key="item.id"
                :label="item.dictName"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="规格条码:">
            <el-input v-model="data.specBarCode" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="规格编码:">
            <el-input v-model="data.specCode" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="品牌:">
            <el-select
              v-model="brand"
              value-key="id"
              placeholder="请选择"
              style="width: 100%"
              @change="brandChg"
            >
              <el-option
                v-for="item in brandList"
                :key="item.id"
                :label="item.dictName"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="材质:">
            <el-select
              v-model="material"
              value-key="id"
              placeholder="请选择"
              style="width: 100%"
              @change="materialChg"
            >
              <el-option
                v-for="item in materialList"
                :key="item.id"
                :label="item.dictName"
                :value="item"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="单重:">
            <el-input v-model="data.weight" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="外形尺寸:">
            <el-input v-model="data.size" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="产品图号:">
            <el-input v-model="data.productNumber" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工厂图号:">
            <el-input v-model="data.factoryNumber" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="原装图号:">
            <el-input v-model="data.originalNumber" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="库存:">
            <el-input v-model="data.inventory" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="价格:">
            <el-input
              v-model="data.price"
              placeholder="请输入价格"
              :formatter="
                value => `$ ${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
              "
              :parser="value => value.replace(/\$\s?|(,*)/g, '')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序:">
            <el-input v-model="data.sorts" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="低库存预警值:">
            <el-input v-model="data.min" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="高库存预警值:">
            <el-input v-model="data.max" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="品牌资料:">
            <wangEdit ref="brandDetailRef" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="产品详情:">
            <wangEdit ref="detailRef" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12" style="text-align: right">
          <el-button type="primary" @click="save">保存</el-button>
        </el-col>
        <el-col :span="12">
          <el-button type="info" style="margin-left: 50px" @click="cls"
            >取消</el-button
          >
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<!--vue 组件选项定义-->
<script setup>
import { ref, onBeforeMount } from "vue";
import { ElMessage } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import host from "@/utils/env.js";
import wangEdit from "@/components/wangEdit/wangEdit.vue";
import { queryByType, queryTree } from "@/api/system/dict.js";
import {
  saveProduct,
  getProductById,
  updateProduct
} from "@/api/product/product.js";
import { useRouter, useRoute } from "vue-router";
//获取路由实例
const route = useRoute();
const router = useRouter();
//单张图片上传
const imageUrl = ref("");
//轮播图，多张图片上传
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const fileList = ref([]);

//品牌详情同名引用
const brandDetailRef = ref(null);
//产品详情同名引用
const detailRef = ref(null);
//产品分类
const productcategorys = ref([]);
//产品类
const category = ref({});
//产品品牌
const brand = ref({});
//产品材质
const material = ref({});

//型号列表
const specList = ref([]);
//品牌列表
const brandList = ref([]);
//材质列表
const materialList = ref([]);
//响应式对象
const data = ref({
  id: "",
  code: "",
  name: "",
  type: "",
  unit: "",
  picurl: "",
  categoryPath: "",
  categoryName: "",
  spec: "",
  specBarCode: "",
  specCode: "",
  brandId: "",
  brandName: "",
  materialId: "",
  materialName: "",
  weight: "",
  size: "",
  productNumber: "",
  factoryNumber: "",
  originalNumber: "",
  inventory: "",
  price: "",
  sorts: "",
  min: "",
  max: "",
  brandDetail: "",
  detail: "",
  CreateUser: "",
  userCode: "",
  banner: []
});
//给品牌赋值
function brandChg(b) {
  data.value.brandId = b.id;
  data.value.brandName = b.dictName;
}
//给产品分类赋值
function categoryChg(selectedValue) {
  const selectedNode = productcategorys.value.find(
    node => node.dictName === selectedValue
  );
  if (selectedNode) {
    data.value.categoryPath = selectedNode.dictCode;
    data.value.categoryName = selectedNode.dictName;
  }
}
//给材质赋值
function materialChg(m) {
  data.value.materialId = m.id;
  data.value.materialName = m.dictName;
}

/**
 * 上传成功
 * @param response
 * @param uploadFile
 */
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    //上传成功
    imageUrl.value = URL.createObjectURL(uploadFile.raw);
    data.value.picurl = response.data;
  }
};

/**
 * 文件上传前的限制
 * @param rawFile
 */
const beforeAvatarUpload = rawFile => {
  if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
    ElMessage.error("请上传jpg、png格式的文件");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error("图片不能超过2MB!");
    return false;
  }
  return true;
};

//轮播图上传
const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = uploadFile => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};
const handleBannerSuccess = (response, uploadFiles) => {
  if (response.code == 200) {
    console.log(data.value, ">>>>>>>>>>>>>");
    data.value.banner.push(response.data);
  }
};

async function init() {
  if (route.query.id) {
    let res = await getProductById(route.query.id);
    if (res.code == 200) {
      data.value = res.data;
      brandDetailRef.value.valueHtml = data.value.brandDetail;
      detailRef.value.valueHtml = data.value.detail;
    }
  }
  let cate = await queryTree("category");
  let specs = await queryByType("spec");
  let brands = await queryByType("brand");
  let materials = await queryByType("material");
  productcategorys.value = cate.data;
  specList.value = specs.data;
  brandList.value = brands.data;
  materialList.value = materials.data;
  brand.value = null;
  category.value = null;
  material.value = null;
  data.value.banner = [];
}

//保存
async function save() {
  //
  data.value.brandDetail = brandDetailRef.value.valueHtml;
  data.value.detail = detailRef.value.valueHtml;
  let res = ref(null);
  if (data.value.id == undefined || data.value.id == "") {
    //新增
    res.value = await saveProduct(data.value);
  } else {
    res.value = await updateProduct(data.value);
  }
  if (res.value.code == 200) {
    ElMessage({
      message: "保存成功",
      type: "success"
    });
    cls();
  }
}
//取消清空数据，并跳转页面
function cls() {
  data.value = {};
  router.push({ path: "/product/list" });
}

onBeforeMount(() => {
  init();
});
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.root {
  width: 95vw;
  background-color: #fff;
  border-radius: 5px;
}
.basic {
  font-size: 24px;
  font-weight: bold;
  color: #0054a6;
  margin-left: 30px;
  margin-top: 20px;
  display: inline-block;

  border-style: none;
  border-left: #0054a6 solid 4px;
  padding-left: 10px;
}

.avatar-uploader .avatar {
  width: 60px;
  height: 60px;
  display: block;
}
</style>
<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 60px;
  height: 60px;
  text-align: center;
}
.el-upload--picture-card {
  height: 60px;
  width: 60px;
}
</style>
